package com.yuelan.apartment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuelan.apartment.domain.Notice;
import com.yuelan.apartment.mapper.NoticeMapper;
import com.yuelan.apartment.service.NoticeService;
import com.yuelan.common.core.constant.HttpStatus;
import com.yuelan.common.core.context.SecurityContextHolder;
import com.yuelan.common.core.utils.DateUtils;
import com.yuelan.common.core.utils.uuid.IdWorker;
import com.yuelan.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

/**
 * @description: 公告
 * @Author: ZhaoYi
 * @date: 24-6-29 20:02
 */

@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    @CacheEvict(value = "noticeList", allEntries = true)
    public int publishNotice(Notice notice) {
        notice.setId(IdWorker.snowflake());
        notice.setUserId(SecurityContextHolder.getUserId());
        notice.setCreateTime(DateUtils.getNowDate());
        notice.setUpdateTime(DateUtils.getNowDate());
        return noticeMapper.insert(notice);
    }

    @Override
    public Notice view(Long id) {
        return noticeMapper.selectById(id);
    }

    @Override
    @CachePut(value = "noticeList")
    public TableDataInfo noticeList(int pageNum, int pageSize) {
        LambdaQueryWrapper<Notice> noticeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        noticeLambdaQueryWrapper.eq(Notice::getUserId, SecurityContextHolder.getUserId());

        Page<Notice> noticePage = new Page<>(pageNum, pageSize);
        Page<Notice> noticePageData = noticeMapper.selectPage(noticePage , noticeLambdaQueryWrapper);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(noticePageData.getRecords());
        rspData.setTotal(noticePageData.getTotal());
        return rspData;
    }

    @Override
    @CacheEvict(value = "noticeList", allEntries = true)
    public int removeNotice(Long id) {
        return noticeMapper.deleteById(id);
    }

    @Override
    @CacheEvict(value = "noticeList", allEntries = true)
    public int editNotice(Notice notice) {
        LambdaUpdateWrapper<Notice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Notice::getId, notice.getId());
        notice.setCreateTime(DateUtil.date());
        notice.setUpdateTime(DateUtil.date());
        return noticeMapper.update(notice, updateWrapper);
    }

}
